﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;

namespace NetfractionHub.LocalMachine.BotCommands.Handler
{
    [CommandHandler("pass")]
    public class SetPassword : CommandHandler
    {
        public override BotReturnStatus HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
        {
            if (message.UnnamedArguments.Count == 1)
            {
                RemoteMachine.Node user = Network.ConnectionManager.GetConnectedNodeByNickname(source.Identity.Nickname);
                if (user != null)
                {
                    if (user.SecurityIdentity.NewPasswordRequestActive)
                    {
                        user.SecurityIdentity.Password = message.UnnamedArguments[0];
                        user.SecurityIdentity.NewPasswordRequestActive = false;

                        if (user.SecurityIdentity.IsRegistered)
                        {
                            // send password changed msg
                            this.ParentBot.SendPrivateMessageFromBot(user, "You have successfully changed your password.");
                        }
                        else
                        {
                            user.SecurityIdentity.Name = source.Identity.Nickname;
                            user.SecurityIdentity.ClientId = source.Identity.ClientId;
                            user.SecurityIdentity.IsRegistered = true;
                            bool regSuccess = Security.IdentityManager.RegisterIdentity(user.SecurityIdentity);

                            if (regSuccess)
                            {
                                this.ParentBot.SendPrivateMessageFromBot(user, "You have successfully registered on the hub.");
                            }
                            else
                            {
                                this.ParentBot.SendPrivateMessageFromBot(user, "Failed to register. A matching identity is already registered.");
                            }
                        }
                    }
                    else
                    {
                        this.ParentBot.SendEchoMessageFromBot(user, "Your password can not be changed, no change request is active. Try !resetpass.");
                    }
                }
            }
            else
            {
                return false;
            }
            return true;
        }
    }
}
